package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.TypeClass;
import cn.imvc.app.repositories.TypeClassRepository;
import cn.imvc.app.repositories.TypeValueRepository;
import cn.imvc.data.domain.ViewRequest;
/**
 * 
 * @author zhanghy
 * @date 2016年8月11日上午9:58:06
 *
 */
@Service
public class TypeClassModelImpl implements TypeClassModel{
  
	@Autowired
	TypeClassRepository typeClassRepository;
	@Autowired
	TypeValueRepository typeValueRepository;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<TypeClass> find(ViewRequest viewRequest) {
		return typeClassRepository.findAll(viewRequest);
	}

	public int save(TypeClass typeClass) {
		String code = typeClass.getCode();
		String name = typeClass.getName();
		List<TypeClass> listCode = typeClassRepository.getByCode(code);
		List<TypeClass> listName = typeClassRepository.getByName(name);
		if(listCode.size()>0){
			return 0;
		}else if(listName.size()>0){
			return -1;
		}
		typeClassRepository.saveAndFlush(typeClass);
		return 1;
	}

	public int update(int id,TypeClass typeClass) {
		TypeClass loadTypeClass = typeClassRepository.getOne(id);
		String code = typeClass.getCode();
		String name = typeClass.getName(); 
		List<TypeClass> listCode = typeClassRepository.getByCode(code);
		List<TypeClass> listName = typeClassRepository.getByName(name);
		if(listCode.size()>0&&!code.equals(loadTypeClass.getCode())){
			return 0;
		}else if(listName.size()>0&&!name.equals(loadTypeClass.getName())){
			return -1;
		}
		BeanUtils.copyProperties(typeClass, loadTypeClass, new String[]{"id"});
		typeClassRepository.saveAndFlush(loadTypeClass);
		return 1;
	}

	public TypeClass get(int id) {
		return typeClassRepository.getOne(id);
	}

	public String delete(int id) {
		  String result = refRelationModel.deleteDateCheck("Type_Class", "id", id);
		    if(result.equals("")){
		    	typeClassRepository.delete(id);
		    	return "";
		    }else{
		    	return result;
		    }
	}

	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			typeClassRepository.delete(id);
		}
		
	}

}
